<template>
    <el-page-header title="新闻管理" content="创建新闻" icon=""/>
    <el-form ref="newsFormRef" :model="newsForm" :rules="newsFormRules" label-width="80px" class="demo-ruleForm" status-icon>
        <el-form-item label="标题" prop="title">
            <el-input v-model="newsForm.title" auto-complete="off" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
            <editor @event="handleChange" />
        </el-form-item>
        <el-form-item label="类别" prop="category">
            <el-select v-model="newsForm.category" class="m-2" phaceholder="Select" style="width:100%;">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="封面" prop="cover">
            <Upload :avatar="newsForm.cover" @lennoxchange="handleUploadChange"/>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm()">添加新闻</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>
import {ref,reactive} from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import Editor from '../../components/editor/Editor.vue'
import Upload from '../../components/upload/Upload.vue';
import upload from '../../util/upload'

const router = useRouter()
const store = useStore()
const newsFormRef = ref()
const newsForm = reactive({
    title: '',
    content: '',
    category: 1, //1最近动态，2典型案例，3通告公告
    cover: '',
    file:null,
    author: store.state.userInfo.username,
    isPublish: 0 //0未发布，1已发布
})
const newsFormRules = {
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
    ],
    content: [
        { required: true, message: '请输入内容', trigger: 'blur'},
    ],
    category: [
        { required: true, message: '请选择分类', trigger: 'blur'},
    ],
    cover: [
        { required: true, message: '请上传封面', trigger: 'blur'},
    ]
}
const options = [
    {
        value: 1,
        label: '最近动态'
    },
    {
        value: 2,
        label: '典型案例'
    },
    {
        value: 3,
        label: '通告公告'
    }
]

const handleChange = (data) => {
    newsForm.content = data
}

const handleUploadChange = (file) => {
    newsForm.cover = URL.createObjectURL(file)
    newsForm.file = file
}

const submitForm = () => {
    newsFormRef.value.validate(async (valid) => {
        if (valid) {
            console.log(newsForm)
            const res = await upload('/adminapi/news/add', newsForm)            
            if(res.ActionType === "OK"){
                ElMessage({
                    type: 'success',
                    message: '添加新闻成功'
                })
                router.push('/news-manage/newslist')
            }
        }
    })
}
</script>

<style lang="scss" scoped>
.demo-ruleForm {
    margin-top: 50px;
}
</style>